<template>
  <div class="ticket-management">
    <!-- 页面标题和操作栏 -->
    <div class="page-header">
      <div class="header-left">
        <h1 class="page-title">工单管理</h1>
        <p class="page-description">管理和跟踪所有工单的处理状态</p>
      </div>
      <div class="header-actions">
        <el-button type="primary" :icon="Plus" @click="showCreateTicketDialog">
          创建工单
        </el-button>
      </div>
    </div>

    <!-- 工具栏：筛选和搜索 -->
    <div class="toolbar">
      <div class="toolbar-left">
        <!-- 搜索框 -->
        <el-input
          v-model="searchKeyword"
          placeholder="搜索工单ID、标题、分配用户..."
          prefix-icon="Search"
          style="width: 300px;"
          @keyup.enter="handleSearch"
          clearable
        />
        
        <!-- 筛选器 -->
        <el-select v-model="filterStatus" placeholder="状态筛选" style="width: 120px;" clearable>
          <el-option label="全部" value="" />
          <el-option label="待处理" value="pending" />
          <el-option label="进行中" value="in-progress" />
          <el-option label="已完成" value="completed" />
          <el-option label="已归档" value="archived" />
        </el-select>
        
        <el-select v-model="filterPriority" placeholder="优先级筛选" style="width: 120px;" clearable>
          <el-option label="全部" value="" />
          <el-option label="高" value="high" />
          <el-option label="中" value="medium" />
          <el-option label="低" value="low" />
        </el-select>
        
        <el-select v-model="filterAssignee" placeholder="分配用户" style="width: 140px;" clearable>
          <el-option label="全部" value="" />
          <el-option 
            v-for="user in userList" 
            :key="user.id" 
            :label="user.name" 
            :value="user.id" 
          />
        </el-select>
      </div>
      
      <div class="toolbar-right">
        <!-- 批量操作 -->
        <el-dropdown @command="handleBatchAction" :disabled="selectedTickets.length === 0">
          <el-button :disabled="selectedTickets.length === 0">
            批量操作 ({{ selectedTickets.length }})
            <el-icon><ArrowDown /></el-icon>
          </el-button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="assign">批量分配</el-dropdown-item>
              <el-dropdown-item command="archive">批量归档</el-dropdown-item>
              <el-dropdown-item command="delete" divided>批量删除</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
        
        <!-- 刷新按钮 -->
        <el-button :icon="Refresh" @click="refreshTickets">刷新</el-button>
      </div>
    </div>

    <!-- 工单列表表格 -->
    <div class="ticket-table-container">
      <el-table
        ref="ticketTableRef"
        :data="filteredTickets"
        v-loading="loading"
        @selection-change="handleSelectionChange"
        @row-click="handleRowClick"
        row-key="id"
        stripe
        size="default"
      >
        <!-- 选择列 -->
        <el-table-column type="selection" width="50" />
        
        <!-- 工单ID -->
        <el-table-column prop="id" label="工单ID" width="100" sortable>
          <template #default="{ row }">
            <el-link type="primary" @click.stop="viewTicketDetail(row)">
              #{{ row.id }}
            </el-link>
          </template>
        </el-table-column>
        
        <!-- 标题/摘要 -->
        <el-table-column prop="title" label="标题" min-width="200" show-overflow-tooltip>
          <template #default="{ row }">
            <div class="ticket-title">
              <span class="title-text">{{ row.title }}</span>
              <el-tag v-if="row.isUrgent" type="danger" size="small" class="urgent-tag">
                紧急
              </el-tag>
            </div>
          </template>
        </el-table-column>
        
        <!-- 分配用户 -->
        <el-table-column prop="assignee" label="分配用户" width="140">
          <template #default="{ row }">
            <div class="assignee-info" v-if="row.assignee">
              <el-avatar :size="24" :src="row.assignee.avatar">
                {{ row.assignee.name.charAt(0) }}
              </el-avatar>
              <span class="assignee-name">{{ row.assignee.name }}</span>
            </div>
            <el-text type="info" v-else>未分配</el-text>
          </template>
        </el-table-column>
        
        <!-- 优先级 -->
        <el-table-column prop="priority" label="优先级" width="100">
          <template #default="{ row }">
            <el-tag 
              :type="getPriorityType(row.priority)" 
              size="small"
              class="priority-tag"
            >
              {{ getPriorityText(row.priority) }}
            </el-tag>
          </template>
        </el-table-column>
        
        <!-- 状态 -->
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag 
              :type="getStatusType(row.status)" 
              size="small"
              class="status-tag"
            >
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        
        <!-- 创建时间 -->
        <el-table-column prop="createdAt" label="创建时间" width="160" sortable>
          <template #default="{ row }">
            {{ formatDateTime(row.createdAt) }}
          </template>
        </el-table-column>
        
        <!-- SLA时效 -->
        <el-table-column prop="sla" label="SLA时效" width="120">
          <template #default="{ row }">
            <div class="sla-info">
              <el-progress 
                :percentage="getSLAPercentage(row)" 
                :color="getSLAColor(row)"
                :stroke-width="6"
                :show-text="false"
              />
              <span class="sla-text" :class="getSLATextClass(row)">
                {{ getSLAText(row) }}
              </span>
            </div>
          </template>
        </el-table-column>
        
        <!-- 操作列 -->
        <el-table-column label="操作" width="120" fixed="right">
          <template #default="{ row }">
            <el-button-group size="small">
              <el-button 
                type="primary" 
                :icon="View" 
                @click.stop="viewTicketDetail(row)"
                title="查看详情"
              />
              <el-button 
                type="warning" 
                :icon="Edit" 
                @click.stop="editTicket(row)"
                title="编辑"
              />
              <el-button 
                type="danger" 
                :icon="Delete" 
                @click.stop="deleteTicket(row)"
                title="删除"
              />
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="totalTickets"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 创建/编辑工单对话框 -->
    <TicketDialog
      v-model="showTicketDialog"
      :ticket="editingTicket"
      :user-list="userList"
      @success="handleTicketSuccess"
    />
    
    <!-- 工单详情对话框 -->
    <TicketDetailDialog
      v-model="showDetailDialog"
      :ticket="selectedTicket"
      :user-list="userList"
      @update="handleTicketUpdate"
    />
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Plus, 
  Search, 
  Refresh, 
  ArrowDown, 
  View, 
  Edit, 
  Delete 
} from '@element-plus/icons-vue'

// 导入子组件
import TicketDialog from './TicketDialog.vue'
import TicketDetailDialog from './TicketDetailDialog.vue'

console.log('工单管理组件加载')

// 响应式数据
const loading = ref(false)
const searchKeyword = ref('')
const filterStatus = ref('')
const filterPriority = ref('')
const filterAssignee = ref('')
const selectedTickets = ref([])
const currentPage = ref(1)
const pageSize = ref(20)
const totalTickets = ref(0)

// 对话框控制
const showTicketDialog = ref(false)
const showDetailDialog = ref(false)
const editingTicket = ref(null)
const selectedTicket = ref(null)

// 表格引用
const ticketTableRef = ref()

// 用户列表
const userList = ref([
  { id: 1, name: '张三', avatar: '' },
  { id: 2, name: '李四', avatar: '' },
  { id: 3, name: '王五', avatar: '' },
  { id: 4, name: '赵六', avatar: '' }
])

// 工单列表数据
const ticketList = ref([
  {
    id: 'T001',
    title: '系统登录异常，无法正常访问',
    assignee: { id: 1, name: '张三', avatar: '' },
    priority: 'high',
    status: 'pending',
    createdAt: '2025-01-15 09:30:00',
    slaDeadline: '2025-01-15 17:30:00',
    isUrgent: true,
    description: '用户反馈系统登录页面加载缓慢，输入用户名密码后无响应'
  },
  {
    id: 'T002',
    title: '数据报表导出功能故障',
    assignee: { id: 2, name: '李四', avatar: '' },
    priority: 'medium',
    status: 'in-progress',
    createdAt: '2025-01-15 10:15:00',
    slaDeadline: '2025-01-16 10:15:00',
    isUrgent: false,
    description: '财务部门反馈月度报表无法正常导出Excel格式'
  },
  {
    id: 'T003',
    title: '新用户权限配置需求',
    assignee: { id: 3, name: '王五', avatar: '' },
    priority: 'low',
    status: 'completed',
    createdAt: '2025-01-14 14:20:00',
    slaDeadline: '2025-01-17 14:20:00',
    isUrgent: false,
    description: '人事部门新入职员工需要配置系统访问权限'
  },
  {
    id: 'T004',
    title: '数据库性能优化建议',
    assignee: null,
    priority: 'medium',
    status: 'pending',
    createdAt: '2025-01-15 11:45:00',
    slaDeadline: '2025-01-16 11:45:00',
    isUrgent: false,
    description: '系统响应速度较慢，需要对数据库进行性能分析和优化'
  },
  {
    id: 'T005',
    title: '移动端适配问题修复',
    assignee: { id: 4, name: '赵六', avatar: '' },
    priority: 'high',
    status: 'in-progress',
    createdAt: '2025-01-15 08:00:00',
    slaDeadline: '2025-01-15 20:00:00',
    isUrgent: true,
    description: '移动设备访问系统时页面布局错乱，需要紧急修复'
  }
])

// 计算属性：筛选后的工单列表
const filteredTickets = computed(() => {
  let result = ticketList.value

  // 关键词搜索
  if (searchKeyword.value) {
    const keyword = searchKeyword.value.toLowerCase()
    result = result.filter(ticket => 
      ticket.id.toLowerCase().includes(keyword) ||
      ticket.title.toLowerCase().includes(keyword) ||
      (ticket.assignee?.name || '').toLowerCase().includes(keyword)
    )
  }

  // 状态筛选
  if (filterStatus.value) {
    result = result.filter(ticket => ticket.status === filterStatus.value)
  }

  // 优先级筛选
  if (filterPriority.value) {
    result = result.filter(ticket => ticket.priority === filterPriority.value)
  }

  // 分配用户筛选
  if (filterAssignee.value) {
    result = result.filter(ticket => ticket.assignee?.id === filterAssignee.value)
  }

  totalTickets.value = result.length
  return result
})

// 页面初始化
onMounted(() => {
  console.log('工单管理组件初始化')
  refreshTickets()
})

// 刷新工单列表
const refreshTickets = async () => {
  console.log('刷新工单列表')
  loading.value = true
  
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 500))
    
    ElMessage.success('工单列表刷新成功')
  } catch (error) {
    console.error('刷新工单列表失败:', error)
    ElMessage.error('刷新失败，请重试')
  } finally {
    loading.value = false
  }
}

// 搜索处理
const handleSearch = () => {
  console.log('搜索工单:', searchKeyword.value)
  currentPage.value = 1
}

// 选择变更处理
const handleSelectionChange = (selection) => {
  selectedTickets.value = selection
  console.log('选中的工单:', selection.map(t => t.id))
}

// 行点击处理
const handleRowClick = (row) => {
  console.log('点击工单行:', row.id)
  viewTicketDetail(row)
}

// 批量操作处理
const handleBatchAction = async (command) => {
  console.log('批量操作:', command, selectedTickets.value.map(t => t.id))
  
  if (selectedTickets.value.length === 0) {
    ElMessage.warning('请先选择要操作的工单')
    return
  }
  
  try {
    const confirmed = await ElMessageBox.confirm(
      `确定要对选中的 ${selectedTickets.value.length} 个工单执行${command}操作吗？`,
      '批量操作确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    if (confirmed) {
      // 模拟批量操作
      loading.value = true
      await new Promise(resolve => setTimeout(resolve, 1000))
      
      ElMessage.success(`批量${command}操作完成`)
      selectedTickets.value = []
      refreshTickets()
    }
  } catch (error) {
    console.log('用户取消批量操作')
  } finally {
    loading.value = false
  }
}

// 分页处理
const handleSizeChange = (newSize) => {
  console.log('页面大小变更:', newSize)
  pageSize.value = newSize
  currentPage.value = 1
}

const handleCurrentChange = (newPage) => {
  console.log('页码变更:', newPage)
  currentPage.value = newPage
}

// 显示创建工单对话框
const showCreateTicketDialog = () => {
  console.log('显示创建工单对话框')
  editingTicket.value = null
  showTicketDialog.value = true
}

// 查看工单详情
const viewTicketDetail = (ticket) => {
  console.log('查看工单详情:', ticket.id)
  selectedTicket.value = ticket
  showDetailDialog.value = true
}

// 编辑工单
const editTicket = (ticket) => {
  console.log('编辑工单:', ticket.id)
  editingTicket.value = { ...ticket }
  showTicketDialog.value = true
}

// 删除工单
const deleteTicket = async (ticket) => {
  console.log('删除工单:', ticket.id)
  
  try {
    const confirmed = await ElMessageBox.confirm(
      `确定要删除工单 #${ticket.id} 吗？此操作不可恢复。`,
      '删除确认',
      {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'error'
      }
    )
    
    if (confirmed) {
      // 模拟删除操作
      const index = ticketList.value.findIndex(t => t.id === ticket.id)
      if (index > -1) {
        ticketList.value.splice(index, 1)
        ElMessage.success('工单删除成功')
      }
    }
  } catch (error) {
    console.log('用户取消删除')
  }
}

// 工单操作成功处理
const handleTicketSuccess = (ticket) => {
  console.log('工单操作成功:', ticket)
  
  if (editingTicket.value) {
    // 更新现有工单
    const index = ticketList.value.findIndex(t => t.id === ticket.id)
    if (index > -1) {
      ticketList.value[index] = { ...ticket }
    }
    ElMessage.success('工单更新成功')
  } else {
    // 添加新工单
    ticketList.value.unshift({
      ...ticket,
      id: `T${String(ticketList.value.length + 1).padStart(3, '0')}`
    })
    ElMessage.success('工单创建成功')
  }
  
  showTicketDialog.value = false
  editingTicket.value = null
}

// 工单更新处理
const handleTicketUpdate = (ticket) => {
  console.log('工单更新:', ticket)
  handleTicketSuccess(ticket)
  showDetailDialog.value = false
}

// 工具函数
const getPriorityType = (priority) => {
  const types = {
    high: 'danger',
    medium: 'warning',
    low: 'info'
  }
  return types[priority] || 'info'
}

const getPriorityText = (priority) => {
  const texts = {
    high: '高',
    medium: '中',
    low: '低'
  }
  return texts[priority] || '未知'
}

const getStatusType = (status) => {
  const types = {
    pending: 'warning',
    'in-progress': 'primary',
    completed: 'success',
    archived: 'info'
  }
  return types[status] || 'info'
}

const getStatusText = (status) => {
  const texts = {
    pending: '待处理',
    'in-progress': '进行中',
    completed: '已完成',
    archived: '已归档'
  }
  return texts[status] || '未知'
}

const formatDateTime = (dateTime) => {
  return new Date(dateTime).toLocaleString('zh-CN')
}

const getSLAPercentage = (ticket) => {
  const now = new Date()
  const created = new Date(ticket.createdAt)
  const deadline = new Date(ticket.slaDeadline)
  
  const totalTime = deadline.getTime() - created.getTime()
  const usedTime = now.getTime() - created.getTime()
  
  return Math.min(Math.max((usedTime / totalTime) * 100, 0), 100)
}

const getSLAColor = (ticket) => {
  const percentage = getSLAPercentage(ticket)
  if (percentage >= 90) return '#f56c6c'
  if (percentage >= 70) return '#e6a23c'
  return '#67c23a'
}

const getSLAText = (ticket) => {
  const now = new Date()
  const deadline = new Date(ticket.slaDeadline)
  const diff = deadline.getTime() - now.getTime()
  
  if (diff <= 0) return '已超时'
  
  const hours = Math.floor(diff / (1000 * 60 * 60))
  const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60))
  
  if (hours > 0) return `${hours}h ${minutes}m`
  return `${minutes}m`
}

const getSLATextClass = (ticket) => {
  const percentage = getSLAPercentage(ticket)
  if (percentage >= 90) return 'sla-danger'
  if (percentage >= 70) return 'sla-warning'
  return 'sla-normal'
}
</script>

<style scoped>
.ticket-management {
  height: 100%;
  display: flex;
  flex-direction: column;
}

/* 页面标题 */
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 24px;
}

.header-left {
  flex: 1;
}

.page-title {
  font-size: 24px;
  font-weight: 600;
  color: #1f2937;
  margin: 0 0 8px 0;
}

.page-description {
  font-size: 14px;
  color: #6b7280;
  margin: 0;
}

.header-actions {
  display: flex;
  gap: 12px;
}

/* 工具栏 */
.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 16px;
  background: #ffffff;
  border-radius: 8px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.toolbar-left {
  display: flex;
  gap: 12px;
  align-items: center;
}

.toolbar-right {
  display: flex;
  gap: 12px;
  align-items: center;
}

/* 表格容器 */
.ticket-table-container {
  flex: 1;
  background: #ffffff;
  border-radius: 8px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

/* 表格样式 */
.ticket-title {
  display: flex;
  align-items: center;
  gap: 8px;
}

.title-text {
  flex: 1;
}

.urgent-tag {
  flex-shrink: 0;
}

.assignee-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.assignee-name {
  font-size: 13px;
  color: #374151;
}

.priority-tag,
.status-tag {
  font-weight: 500;
}

.sla-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.sla-text {
  font-size: 12px;
  text-align: center;
}

.sla-normal {
  color: #16a34a;
}

.sla-warning {
  color: #d97706;
}

.sla-danger {
  color: #dc2626;
}

/* 分页 */
.pagination-container {
  padding: 16px;
  border-top: 1px solid #e5e7eb;
  display: flex;
  justify-content: center;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    gap: 16px;
  }
  
  .toolbar {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
  }
  
  .toolbar-left,
  .toolbar-right {
    flex-wrap: wrap;
  }
  
  .ticket-table-container {
    overflow-x: auto;
  }
}
</style>
